package com.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.common.to.es.SkuEsModel;
import com.search.config.ElasticSearchConfig;
import com.search.constant.EsConstant;
import com.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-03-28 21:48
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    /**
     * 添加数据到 ES
     * @param skuEsModelList
     * @throws IOException
     */
    @Override
    public void productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        // 1、创建索引
        // 2、设置 ES 保存数据
        BulkRequest bulkRequest = new BulkRequest();        // bulk 批处理
        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String esContentJason = JSON.toJSONString(skuEsModel);
            indexRequest.source(esContentJason, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        // 3、保存到 ES
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // 4、处理可能出现的异常
        boolean hasFailures = bulkResponse.hasFailures();
        if(hasFailures){
            String errorIdList = Arrays.asList(bulkResponse.getItems()).toString();
            log.error("ES 添加发生异常",errorIdList);
        }


    }
}
